<?php
/**
 * Created by PhpStorm.
 * Author: sitewang@aliyun.com
 * CreateTime: 2023/11/6 22:35
 * Blog：www.myblogs.xyz
 */

namespace app\infrastructure\model;

use app\infrastructure\helper\ResponseHelper;
use think\facade\Validate;

trait InsertTrait
{
	/**
	 * 更新单条数据
	 * @param string|array $where
	 * @param array $data
	 * @return bool
	 */
	public function setField($where = '',array $data = []): bool
	{
		if (empty($data)) return false;
		return $this->query($where)->save($data);
	}

	/**
	 * 更新和修改操作
	 * @param array $data
	 * @param array $validateRule
	 * @param bool $all
	 * @param bool $getLastInsID
	 * @return bool|string
	 */
	public function saveData(array $data = [] , array $validateRule = [], bool $all = false, bool $getLastInsID = false)
	{
		// $all 是否批量操作
		if ($validateRule){
			$validate = false;
			if (is_array($validateRule)){
				if (!empty($validateRule['rule'])){
					$validate = Validate::make($validateRule['rule'], $validateRule['message']);
				}
			}
			if (!$validate){
				return ResponseHelper::setError('验证失败');
			}
			// 是否批量验证
			if ($all){
				foreach ($data as $val){
					if (!$validate->check($val)){
						return ResponseHelper::setError($validate->getError());
					}
				}
			}else{
				if (!$validate->check($data)){
					return ResponseHelper::setError($validate->getError());
				}
			}
		}
		if ($all){
			$rows = $this->insertAll($data);
		}else{
			if (empty($data[$this->pk])){
				$rows = self::create($data);
				if ($getLastInsID === true){
					return $this->getLastInsID();
				}
			}else{
				$rows = self::update($data);
			}
		}
		if (empty($rows)){
			return false;
		}
		return true;
	}
}